package com.we.risk.registerchanneldeprecated.basicinfo.dim;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TableHfqOrigin {
    public static Logger LOG = LoggerFactory.getLogger(TableHfqOrigin.class);
    public static final String KFKTABLE = "fdm.rrd03_hfq_origin";
    public static final String QUERYSQL =
            "select origin as origin_name, "
                    + "growing_code as origin_connect_id, "
                    + "unix_timestamp(date_format(update_time,'yyyy-MM-dd HH:mm:ss')) as update_time "
                    + "from "
                    + KFKTABLE
                    + " where growing_code is not null "
                    + "and growing_code <> ''";

    public String origin_name;
    public String origin_connect_id;
    public long update_time;

    public TableHfqOrigin() {}

    public TableHfqOrigin(String origin_name, String origin_connect_id, long update_time) {
        this.origin_name = origin_name;
        this.origin_connect_id = origin_connect_id;
        this.update_time = update_time;
    }

    public static TableHfqOrigin init(String origin_connect_id) {
        return new TableHfqOrigin("", origin_connect_id, -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableHfqOrigin.QUERYSQL);
        DataStream<Tuple2<Boolean, TableHfqOrigin>> inputStream =
                tableEnv.toRetractStream(tableRes, TableHfqOrigin.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableHfqOrigin>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableHfqOrigin> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableHfqOrigin>, String>() {
                                    @Override
                                    public String getKey(Tuple2<Boolean, TableHfqOrigin> value)
                                            throws Exception {
                                        return value.f1.getOrigin_connect_id();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<Tuple2<Boolean, TableHfqOrigin>, String>() {
                                    ValueState<TableHfqOrigin> hfqOriginVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        hfqOriginVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableHfqOrigin>(
                                                                        "hfqOriginVState",
                                                                        TableHfqOrigin.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableHfqOrigin> value,
                                            Collector<String> out)
                                            throws Exception {
                                        String origin_connect_id = value.f1.getOrigin_connect_id();
                                        String origin_name = value.f1.getOrigin_name();
                                        long update_time = value.f1.getUpdate_time();

                                        // LOG.warn("input origin_connect_id: " + origin_connect_id
                                        // + " origin_name: " + origin_name + " update_time:" +
                                        // update_time);

                                        TableHfqOrigin tmpState = hfqOriginVState.value();
                                        TableHfqOrigin curState =
                                                (tmpState == null
                                                        ? TableHfqOrigin.init(origin_connect_id)
                                                        : tmpState);

                                        // LOG.warn("state update_time: " +
                                        // curState.getUpdate_time() + " origin_name: " +
                                        // origin_name);
                                        if (update_time > curState.getUpdate_time()
                                                && !origin_name.equals(curState.getOrigin_name())) {
                                            JSONObject outJSon = new JSONObject();
                                            outJSon.put("origin_connect_id", origin_connect_id);
                                            outJSon.put("origin_name", origin_name);
                                            out.collect(outJSon.toString());

                                            curState.update_time = update_time;
                                            curState.origin_name = origin_name;
                                            hfqOriginVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public String getOrigin_connect_id() {
        return origin_connect_id;
    }

    public String getOrigin_name() {
        return origin_name;
    }

    public long getUpdate_time() {
        return update_time;
    }
}
